<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta name="msapplication-TileImage" content="/icon.png">
    <link rel="icon" href="/icon.png">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件下载</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }

        h1 {
            color: #333;
        }

        ul {
            list-style-type: none;
            padding: 0;
        }

        li {
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 20px;
            border-bottom: 1px solid #ddd;
            padding-bottom: 10px;
        }

        li:last-child {
            border-bottom: none;
        }

        a {
            text-decoration: none;
            color :rgb(5, 5, 209);
            border-radius: 4px;
            padding: 2px 2px 2px 2px;
        }

        a:hover {
               background:rgba(5, 5, 209, 0.329);
        }

        #fileInfoModal {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: white;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            z-index: 1000;
        }

        #modalOverlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 999;
        }

        form {
            border: 1px solid #ddd;
            border-radius: 4px;
            /* position: fixed;
            top: 20px;
            right: 20px; */
            background-color: white;
            z-index: 100;
        }

        input[type="file"],
        input[type="text"],
        input[type="submit"] {
            margin: 10px 0;
            padding: 8px;
        }

        #breadcrumb {
            margin-bottom: 20px;
            font-size: 16px;
        }

        #breadcrumb a {
            color: #007BFF;
            text-decoration: underline;
            background-color: transparent;
            padding: 0;
            margin-right: 5px;
            border-bottom: #0056b3 1px solid;
        }

        #breadcrumb a:hover {
            color: #0056b3;
        }

        #breadcrumb a.current {
            font-weight: bold;
        }

        #breadcrumb span {
            margin-right: 5px;
        }

        /* 新增提示框样式 */
        #notification-container {
            position: fixed;
            bottom: 20px;
            right: 20px;
            z-index: 1000;
        }

        .notification {
            padding: 15px;
            margin-top: 10px;
            border-radius: 4px;
            color: white;
            font-weight: bold;
            min-width: 200px;
        }

        .notification.success {
            background-color: #28a745;
        }

        .notification.error {
            background-color: #dc3545;
        }

        /* 新增认证弹窗样式 */
        #authModal {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: white;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            z-index: 1001;
            width: 300px;
        }

        #authModalOverlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
        }

        #authModal h2 {
            margin-top: 0;
            color: #333;
        }

        #authModal input[type="text"] {
            width: 100%;
            padding: 10px;
            margin: 10px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }

        #authModal button {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }

        #authModal button#authSubmit {
            background-color: #007BFF;
            color: white;
        }

        #authModal button#authSubmit:hover {
            background-color: #0056b3;
        }

        #authModal button#authCancel {
            background-color: #f8f9fa;
            color: #333;
        }

        #authModal button#authCancel:hover {
            background-color: #e2e6ea;
        }
        .home-icon {
            position: fixed;
            right: 20px;
            bottom: 20px;
            background-color: #007BFF;
            border: none;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            cursor: pointer;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
            display: flex;
            justify-content: center;
            align-items: center;
            transition: background-color 0.3s;
            padding: 0px 0px 0px 0px;
        }

        .home-icon svg {
            width: 20px;
            height: 20px;
            fill: white;
        }

        .home-icon:hover {
            background-color: #0056b3;
        }
    </style>
</head>

<body>
    <!-- 新增返回主页图标 -->
    <a href="/" class="home-icon">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512">
            <!-- 家的图标路径 -->
            <path d="M575.8 255.5c0 18-15 32.1-32 32.1h-32l.7 160.2c0 2.7-.2 5.4-.5 8.1V472c0 22.1-17.9 40-40 40H456c-1.1 0-2.2 0-3.3-.1c-1.4 .1-2.8 .1-4.2 .1H416 392c-22.1 0-40-17.9-40-40V448 384c0-17.7-14.3-32-32-32H256c-17.7 0-32 14.3-32 32v64 24c0 22.1-17.9 40-40 40H160 128.1c-1.5 0-3-.1-4.5-.2c-1.2 .1-2.4 .2-3.6 .2H104c-22.1 0-40-17.9-40-40V360c0-.9 0-1.9 .1-2.8V287.6H32c-18 0-32-14-32-32.1c0-9 3-17 10-24L266.4 8c7-7 15-8 22-8s15 2 21 7L564.8 231.5c8 7 12 15 11 24z"/>
        </svg>
    </a>
    <div id="breadcrumb"></div>
    <ul id="fileList"></ul>

    <form id="uploadForm" enctype="multipart/form-data">
        <input type="file" name="file" required id="fileInput" style="display: none;">
        <button type="button" id="loginButton">登录</button>

        <input type="button" id="uploadButton" value="上传文件" style="display: none; disabled: 1" >
        <input type="button" id="createFolderButton" value="创建文件夹" style="display: none;">
    </form>
    <div id="uploadMessage"></div>

    <!-- 新增提示框容器 -->
    <div id="notification-container"></div>

    <!-- 新增认证弹窗 -->
    <div id="authModalOverlay"></div>
    <div id="authModal">
        <h2>认证登录</h2>
        <input type="text" name="code" placeholder="输入认证码" required id="authCodeInput">
        <button type="button" id="authSubmit">认证</button>
        <button type="button" id="authCancel">取消</button>
    </div>

    <div id="fileInfoModal">
        <h2 id="modalFileName"></h2>
        <p><strong>大小:</strong> <span id="modalFileSize"></span></p>
        <p><strong>修改时间:</strong> <span id="modalFileModTime"></span></p>
        <p><strong>权限:</strong> <span id="modalFileMode"></span></p>
        <p><strong>是否为目录:</strong> <span id="modalFileIsDir"></span></p>
        <button id="closeModalBtn">关闭</button>
    </div>
    <div id="modalOverlay"></div>

    <script>
        const fileInfoModal = document.getElementById('fileInfoModal');
        const modalOverlay = document.getElementById('modalOverlay');
        const closeModalBtn = document.getElementById('closeModalBtn');
        const breadcrumb = document.getElementById('breadcrumb');
        const fileList = document.getElementById('fileList');

        closeModalBtn.addEventListener('click', () => {
            fileInfoModal.style.display = 'none';
            modalOverlay.style.display = 'none';
        });

        modalOverlay.addEventListener('click', () => {
            fileInfoModal.style.display = 'none';
            modalOverlay.style.display = 'none';
        });

        let currentPath = '';
        // 路径栈，记录访问过的路径
        let pathStack = [];

        // 显示提示框的函数
        function showNotification(message, type) {
            const notificationContainer = document.getElementById('notification-container');
            const notification = document.createElement('div');
            notification.className = `notification ${type}`;
            notification.textContent = message;
            notificationContainer.appendChild(notification);

            // 3 秒后移除提示框
            setTimeout(() => {
                notification.remove();
            }, 3000);
        }

        function updateBreadcrumb() {
            console.log('当前路径 currentPath:', currentPath);
            // 去除末尾斜杠
            let cleanPath = currentPath.replace(/\/+$/, '');
            const pathParts = cleanPath.split('/').filter(part => part !== '');
            console.log('拆分后的路径部分:', pathParts);
            breadcrumb.innerHTML = '<a href="#" data-path="" class="root-path">根目录</a>';
            let currentFullPath = '';
            pathParts.forEach((part, index) => {
                currentFullPath += (index === 0 ? '' : '/') + part;
                console.log('当前拼接的完整路径:', currentFullPath);
                const isCurrent = index === pathParts.length - 1;
                breadcrumb.innerHTML += ` <span>/</span> <a href="#" data-path="${encodeURIComponent(currentFullPath)}" ${isCurrent ? 'class="current"' : ''}>${part}</a>`;
            });
            breadcrumb.querySelectorAll('a').forEach(link => {
                link.addEventListener('click', (e) => {
                    e.preventDefault();
                    const targetPath = decodeURIComponent(link.dataset.path);
                    // 点击面包屑时，更新路径栈
                    const targetIndex = pathStack.indexOf(targetPath);
                    if (targetIndex !== -1) {
                        pathStack = pathStack.slice(0, targetIndex + 1);
                    } else {
                        // 若目标路径不在栈中，清空栈并压入目标路径
                        pathStack = [targetPath];
                    }
                    currentPath = targetPath;
                    console.log('点击面包屑，当前路径:', currentPath, '路径栈:', pathStack);
                    loadFileList();
                });
            });
        }

        function loadFileList() {
            const url = currentPath ? `/list?path=${encodeURIComponent(currentPath)}` : '/list';
            fetch(url)
               .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
               .then(data => {
                    console.log('获取文件列表数据:', data); 
                    fileList.innerHTML = '';
                    if (!Array.isArray(data.files)) {
                        console.log('返回数据格式错误，files 不是数组:', data);
                    } else {
                        data.files.forEach(file => {
                            const listItem = document.createElement('li');
                            // 确保 li 元素使用弹性布局
                            listItem.style.display = 'flex';
                            listItem.style.alignItems = 'center';
                            listItem.style.justifyContent = 'space-between'; // 让元素分散排列

                            if (file.is_dir) {
                                const dirName = document.createElement('span');
                                dirName.textContent = file.name;
                                dirName.style.cursor = 'pointer';
                                dirName.style.color = '#007BFF';
                                dirName.addEventListener('click', () => {
                                    const newPath = currentPath ? `${currentPath}/${file.name}` : file.name;
                                    // 进入新文件夹，将当前路径压入栈
                                    pathStack.push(currentPath);
                                    currentPath = newPath;
                                    console.log('进入新文件夹后，当前路径:', currentPath, '路径栈:', pathStack);
                                    loadFileList();
                                });
                                listItem.appendChild(dirName);

                                // 文件夹删除按钮
                                const deleteDirButton = document.createElement('a');
                                deleteDirButton.textContent = '删除';
                                deleteDirButton.style.marginLeft = 'auto'; // 让按钮靠右显示
                                deleteDirButton.style.cursor = 'pointer';
                                deleteDirButton.addEventListener('click', () => {
                                    debugger
                                    const authCode = localStorage.getItem('authCode');
                                    if (!authCode) {
                                        showNotification('请先进行认证', 'error');
                                        return;
                                    }
    
                                    const path = currentPath ? `${currentPath}/${file.name}` : file.name;
                                    if(!window.confirm(`确认删除   [ /${path} ]    目录和目录下所有文件吗？ 删除将无法恢复请谨慎！`)) {
                                        return;
                                    }
                                    fetch('/delete-dir', {
                                        method: 'POST',
                                        headers: {
                                            'Content-Type': 'application/json'
                                        },
                                        body: JSON.stringify({
                                            code: authCode,
                                            path: path
                                        })
                                    })
                                   .then(response => response.json())
                                   .then(data => {
                                        showNotification(data.message, data.success ? 'success' : 'error');
                                        if (data.success) {
                                            loadFileList();
                                        }
                                    })
                                   .catch(error => {
                                        showNotification('删除目录失败，请稍后重试', 'error');
                                        console.error('删除目录失败:', error);
                                    });
                                });
                                listItem.appendChild(deleteDirButton);
                            } else {
                                const fileName = document.createElement('span');
                                fileName.textContent = file.name;
                                fileName.style.cursor = 'pointer';
                                fileName.addEventListener('click', () => {
                                    const fullPath = currentPath ? `${currentPath}/${file.name}` : file.name;
                                    fetch(`/file-info/${encodeURIComponent(fullPath)}`)
                                        .then(response => response.json())
                                        .then(data => {
                                            document.getElementById('modalFileName').textContent = data.name;
                                            document.getElementById('modalFileSize').textContent = `${(data.size / 1024).toFixed(2)} KB`;
                                            document.getElementById('modalFileModTime').textContent = data.mod_time;
                                            document.getElementById('modalFileMode').textContent = data.mode;
                                            document.getElementById('modalFileIsDir').textContent = data.is_dir ? '是' : '否';
                                            fileInfoModal.style.display = 'block';
                                            modalOverlay.style.display = 'block';
                                        })
                                        .catch(error => console.error('获取文件详细信息失败:', error));
                                });
                                listItem.appendChild(fileName);

                                const sizeSpan = document.createElement('span');
                                sizeSpan.textContent = `${(file.size / 1024).toFixed(2)} KB`;
                                listItem.appendChild(sizeSpan);

                                const modTimeSpan = document.createElement('span');
                                modTimeSpan.textContent = file.mod_time;
                                listItem.appendChild(modTimeSpan);

                                // 创建一个 div 来包裹下载和删除按钮
                                const actionDiv = document.createElement('div');
                                actionDiv.style.display = 'flex'; // 让按钮水平排列
                                actionDiv.style.gap = '10px'; // 按钮间添加间距

                                // 文件删除按钮
                                const deleteFileButton = document.createElement('a');
                                deleteFileButton.textContent = '删除';
                                deleteFileButton.style.display = 'inline-block';
                                deleteFileButton.style.cursor = 'pointer';
                                deleteFileButton.addEventListener('click', () => {
                                    const authCode = localStorage.getItem('authCode');
                                    if (!authCode) {
                                        showNotification('请先进行认证', 'error');
                                        return;
                                    }
                                    const path = currentPath ? `${currentPath}/${file.name}` : file.name;
                                    if(!window.confirm(`确认删除该    [ /${path} ]    文件？ 删除将无法恢复请谨慎！`)) {
                                        return;
                                    }
                                    fetch('/delete-file', {
                                        method: 'POST',
                                        headers: {
                                            'Content-Type': 'application/json'
                                        },
                                        body: JSON.stringify({
                                            code: authCode,
                                            path: path
                                        })
                                    })
                                   .then(response => response.json())
                                   .then(data => {
                                        showNotification(data.message, data.success ? 'success' : 'error');
                                        if (data.success) {
                                            loadFileList();
                                        }
                                    })
                                   .catch(error => {
                                        showNotification('删除文件失败，请稍后重试', 'error');
                                        console.error('删除文件失败:', error);
                                    });
                                });
                                actionDiv.appendChild(deleteFileButton);

                                // 创建 a 标签作为下载链接
                                const downloadLink = document.createElement('a');
                                downloadLink.textContent = '下载';
                                const fullPath = currentPath ? `${currentPath}/${file.name}` : file.name;
                                downloadLink.href = `/download/${encodeURIComponent(fullPath)}`;
                                // 给下载链接添加按钮样式
                                downloadLink.style.display = 'inline-block';
                                downloadLink.style.cursor = 'pointer';
                                actionDiv.appendChild(downloadLink);

                                listItem.appendChild(actionDiv);
                            }

                            fileList.appendChild(listItem);
                        });
                    }
                    // 无论返回数据是否为空，都更新面包屑导航
                    updateBreadcrumb();

                    const shouldShow = pathStack.length > 0;
                    console.log('是否显示返回按钮:', shouldShow);
  
                })
               .catch(error => {
                    console.error('获取文件列表失败:', error);
                    // 即便请求出错，也更新面包屑导航
                    updateBreadcrumb();
                });
        }

        document.addEventListener('DOMContentLoaded', function() {
            loadFileList();
            const uploadForm = document.getElementById('uploadForm');
            const uploadMessage = document.getElementById('uploadMessage');
            const uploadButton = document.getElementById('uploadButton');
            const fileInput = document.getElementById('fileInput');
            const createFolderButton = document.getElementById('createFolderButton');
            const loginButton = document.getElementById('loginButton');

            const authModal = document.getElementById('authModal');
            const authModalOverlay = document.getElementById('authModalOverlay');
            const authCodeInput = document.getElementById('authCodeInput');
            const authSubmit = document.getElementById('authSubmit');
            const authCancel = document.getElementById('authCancel');

            // 尝试从 localStorage 中获取保存的认证码
            const savedAuthCode = localStorage.getItem('authCode');
            if (savedAuthCode) {
                // 模拟认证请求
                verifyAuthCode(savedAuthCode);
            }

            // 点击登录按钮显示认证弹窗
            loginButton.addEventListener('click', () => {
                console.log('点击登录按钮，显示认证弹窗');
                authModal.style.display = 'block';
                authModalOverlay.style.display = 'block';
            });

            // 点击取消按钮隐藏认证弹窗
            authCancel.addEventListener('click', () => {
                authModal.style.display = 'none';
                authModalOverlay.style.display = 'none';
            });

            // 点击遮罩层隐藏认证弹窗
            authModalOverlay.addEventListener('click', () => {
                authModal.style.display = 'none';
                authModalOverlay.style.display = 'none';
            });

            // 点击上传按钮触发文件选择对话框
            uploadButton.addEventListener('click', (e) => {
                e.preventDefault();
                if (uploadButton.disabled) return;
                fileInput.click();
            });

            // 文件选择后直接上传
            fileInput.addEventListener('change', () => {
                if (fileInput.files.length > 0) {
                    const formData = new FormData(uploadForm);
                    // 从 localStorage 中获取认证码并添加到表单数据
                    const authCode = localStorage.getItem('authCode');
                    if (authCode) {
                        formData.append('code', authCode);
                    }
                    // 添加当前路径到表单数据
                    formData.append('path', currentPath); 

                    fetch('/upload', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        showNotification(data.message, data.success ? 'success' : 'error');
                        if (data.success) {
                            // 上传成功后刷新文件列表
                            loadFileList();
                        }
                        // 清空文件选择
                        fileInput.value = ''; 
                    })
                    .catch(error => {
                        showNotification('上传失败，请稍后重试', 'error');
                        console.error('上传失败:', error);
                    });
                }
            });

            // 认证提交按钮点击事件
            authSubmit.addEventListener('click', async () => {
                const authCode = authCodeInput.value;
                if (!authCode) {
                    showNotification('请输入认证码', 'error');
                    return;
                }

                try {
                    const response = await fetch('/authenticate', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ code: authCode })
                    });

                    const data = await response.json();
                    if (data.success) {
                        showNotification('认证成功', 'success');
                        // 隐藏认证弹窗
                        authModal.style.display = 'none';
                        authModalOverlay.style.display = 'none';
                        // 隐藏登录按钮
                        loginButton.style.display = 'none';
                        // 显示上传按钮和创建文件夹按钮
                        uploadButton.style.display = 'inline-block';
                        uploadButton.disabled = false;
                        createFolderButton.style.display = 'inline-block';
                        // 将认证码保存到 localStorage
                        localStorage.setItem('authCode', authCode);
                        isAuthenticated = true; // 认证成功，更新状态
                        loadFileList(); // 重新加载文件列表，显示删除按钮
                    } else {
                        showNotification('认证失败: ' + data.message, 'error');
                        uploadButton.style.display = 'none';
                        uploadButton.disabled = true;
                        createFolderButton.style.display = 'none';
                        isAuthenticated = false; // 认证失败，更新状态
                    }
                } catch (error) {
                    showNotification('认证请求出错: ' + error.message, 'error');
                    uploadButton.style.display = 'none';
                    uploadButton.disabled = true;
                    createFolderButton.style.display = 'none';
                    isAuthenticated = false; // 请求出错，更新状态
                }
            });

            // 创建文件夹按钮点击事件
            createFolderButton.addEventListener('click', async () => {
                const folderName = prompt('请输入文件夹名称:');
                if (folderName) {
                    const authCode = localStorage.getItem('authCode');
                    if (!authCode) {
                        showNotification('请先进行认证', 'error');
                        return;
                    }
                    try {
                        const response = await fetch('/create-folder', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({ 
                                code: authCode,
                                name: folderName,
                                path: currentPath
                            })
                        });

                        const data = await response.json();
                        showNotification(data.message, data.success ? 'success' : 'error');
                        if (data.success) {
                            // 创建成功后刷新文件列表
                            loadFileList();
                        }
                    } catch (error) {
                        showNotification('创建文件夹失败，请稍后重试', 'error');
                        console.error('创建文件夹失败:', error);
                    }
                }
            });

            // 验证认证码的函数
            async function verifyAuthCode(authCode) {
                try {
                    const response = await fetch('/authenticate', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ code: authCode })
                    });

                    const data = await response.json();
                    if (data.success) {
                        // 隐藏登录按钮
                        loginButton.style.display = 'none';
                        // 显示上传按钮和创建文件夹按钮
                        uploadButton.style.display = 'inline-block';
                        uploadButton.disabled = false;
                        createFolderButton.style.display = 'inline-block';
                        isAuthenticated = true; // 认证成功，更新状态
                    } else {
                        // 认证失败，清除保存的认证码
                        localStorage.removeItem('authCode');
                        isAuthenticated = false; // 认证失败，更新状态
                    }
                } catch (error) {
                    // 认证请求出错，清除保存的认证码
                    localStorage.removeItem('authCode');
                    isAuthenticated = false; // 请求出错，更新状态
                }
            }

        });
    </script>
</body>
</html>